package com.idoo.aps.agent;

import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.agent.tool.ToolMethod;
import dev.langchain4j.agent.tool.ToolParam;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentSplitter;
import dev.langchain4j.data.document.splitter.DocumentSplitters;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiEmbeddingModel;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.chroma.ChromaEmbeddingStore;
import dev.langchain4j.store.embedding.EmbeddingMatch;
import dev.langchain4j.store.embedding.EmbeddingSearchRequest;
import dev.langchain4j.store.embedding.EmbeddingSearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Component;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 生产排产智能体核心实现类
 * 
 * @author IDOO Team
 * @version 1.0.0
 */
@Service
public class ProductionIntelligentAgentImpl {

    @Autowired
    private ChatLanguageModel chatLanguageModel;
    
    @Autowired
    private EmbeddingModel embeddingModel;
    
    @Autowired
    private IntentClassifier intentClassifier;
    
    @Autowired
    private ToolRegistry toolRegistry;
    
    @Autowired
    private KnowledgeRAGTool knowledgeRAGTool;
    
    @Autowired
    private DataQueryToolNode dataQueryTool;

    /**
     * 处理用户请求的主入口方法
     */
    public WorkflowResponse processRequest(UserRequest request) {
        try {
            // 1. 入口节点 - 输入预处理
            ProcessedInput processedInput = preprocessInput(request);
            
            // 2. 意图识别节点
            IntentClassificationResult intentResult = intentClassifier.classifyIntent(processedInput);
            
            // 3. 工具选择节点
            List<Tool> selectedTools = toolRegistry.selectTools(intentResult);
            
            // 4. 工具执行节点
            ToolExecutionResult executionResult = executeTools(selectedTools, intentResult, processedInput);
            
            // 5. 结果合成节点
            WorkflowResponse response = synthesizeResponse(executionResult, intentResult, processedInput);
            
            return response;
            
        } catch (Exception e) {
            return handleException(e, request);
        }
    }

    /**
     * 输入预处理方法
     */
    private ProcessedInput preprocessInput(UserRequest request) {
        // 实现输入验证、清洗、实体提取等逻辑
        ProcessedInput processed = new ProcessedInput();
        processed.setCleanedInput(cleanInput(request.getUserInput()));
        processed.setExtractedEntities(extractEntities(request.getUserInput()));
        processed.setMetadata(extractMetadata(request));
        processed.setValid(validateInput(processed));
        processed.setConfidenceScore(calculateConfidenceScore(processed));
        
        return processed;
    }

    private String cleanInput(String input) {
        // 文本清洗逻辑
        return input.trim().replaceAll("[\\r\\n]+", " ").replaceAll("\\s+", " ");
    }

    private List<String> extractEntities(String input) {
        // 实体提取逻辑
        List<String> entities = new ArrayList<>();
        for (EntityType entityType : EntityType.values()) {
            Pattern pattern = entityType.getPattern();
            java.util.regex.Matcher matcher = pattern.matcher(input);
            while (matcher.find()) {
                entities.add(matcher.group());
            }
        }
        return entities;
    }

    private Map<String, Object> extractMetadata(UserRequest request) {
        Map<String, Object> metadata = new HashMap<>();
        metadata.put("timestamp", request.getTimestamp());
        metadata.put("userId", request.getUserId());
        metadata.put("sessionId", request.getSessionId());
        return metadata;
    }

    private boolean validateInput(ProcessedInput input) {
        return input.getCleanedInput() != null && 
               input.getCleanedInput().length() > 0 && 
               input.getCleanedInput().length() <= 1000;
    }

    private double calculateConfidenceScore(ProcessedInput input) {
        // 计算输入质量置信度
        double score = 0.5;
        if (!input.getExtractedEntities().isEmpty()) score += 0.3;
        if (input.getCleanedInput().length() > 10) score += 0.2;
        return Math.min(score, 1.0);
    }

    private ToolExecutionResult executeTools(List<Tool> tools, IntentClassificationResult intent, ProcessedInput input) {
        ToolExecutionResult result = new ToolExecutionResult();
        Map<String, Object> toolResults = new HashMap<>();
        
        for (Tool tool : tools) {
            try {
                Object toolResult = executeTool(tool, intent, input);
                toolResults.put(tool.getClass().getSimpleName(), toolResult);
            } catch (Exception e) {
                toolResults.put(tool.getClass().getSimpleName(), "执行失败: " + e.getMessage());
            }
        }
        
        result.setToolResults(toolResults);
        result.setExecutionTime(System.currentTimeMillis());
        return result;
    }

    private Object executeTool(Tool tool, IntentClassificationResult intent, ProcessedInput input) {
        // 根据工具类型执行相应逻辑
        if (tool instanceof KnowledgeRAGTool) {
            return ((KnowledgeRAGTool) tool).vectorSearch(
                input.getCleanedInput(), 
                KnowledgeType.BEST_PRACTICES, 
                5, 
                0.7
            );
        } else if (tool instanceof DataQueryToolNode) {
            return ((DataQueryToolNode) tool).executeSQLQuery(
                "mes", 
                intent.getParameters(), 
                SecurityLevel.STANDARD
            );
        }
        return null;
    }

    private WorkflowResponse synthesizeResponse(ToolExecutionResult executionResult, IntentClassificationResult intent, ProcessedInput input) {
        WorkflowResponse response = new WorkflowResponse();
        
        // 根据工具执行结果生成最终响应
        String synthesizedAnswer = generateAnswer(executionResult, intent, input);
        
        response.setAnswer(synthesizedAnswer);
        response.setIntent(intent.getPrimaryIntent());
        response.setConfidence(intent.getConfidence());
        response.setExecutionTime(executionResult.getExecutionTime());
        response.setSources(extractSources(executionResult));
        
        return response;
    }

    private String generateAnswer(ToolExecutionResult executionResult, IntentClassificationResult intent, ProcessedInput input) {
        // 使用LLM生成最终回答
        String prompt = buildResponsePrompt(executionResult, intent, input);
        return chatLanguageModel.generate(prompt);
    }

    private String buildResponsePrompt(ToolExecutionResult executionResult, IntentClassificationResult intent, ProcessedInput input) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("# 生产排产智能助手 - 回答生成器\n\n");
        prompt.append("## 用户需求\n");
        prompt.append("原始问题: ").append(input.getCleanedInput()).append("\n");
        prompt.append("意图类型: ").append(intent.getPrimaryIntent()).append("\n\n");
        
        prompt.append("## 工具执行结果\n");
        executionResult.getToolResults().forEach((toolName, result) -> {
            prompt.append("### ").append(toolName).append("\n");
            prompt.append(result.toString()).append("\n\n");
        });
        
        prompt.append("## 回答要求\n");
        prompt.append("请基于以上信息，为用户提供准确、专业、可操作的回答。\n");
        
        return prompt.toString();
    }

    private List<String> extractSources(ToolExecutionResult executionResult) {
        // 从工具执行结果中提取信息来源
        return executionResult.getToolResults().keySet().stream()
            .collect(Collectors.toList());
    }

    private WorkflowResponse handleException(Exception e, UserRequest request) {
        WorkflowResponse response = new WorkflowResponse();
        response.setAnswer("抱歉，处理您的请求时出现了问题。请重新描述您的需求，或联系技术支持。");
        response.setIntent("ERROR");
        response.setConfidence(0.0);
        response.setExecutionTime(System.currentTimeMillis());
        
        // 记录错误日志
        logError(e, request);
        
        return response;
    }

    private void logError(Exception e, UserRequest request) {
        // 实现错误日志记录
        System.err.println("处理请求失败: " + request.getUserInput() + ", 错误: " + e.getMessage());
    }
}

/**
 * 意图识别器
 */
@Component
class IntentClassifier {

    @Autowired
    private ChatLanguageModel llm;
    
    @Autowired
    private FewShotExampleStore exampleStore;
    
    private static final double CONFIDENCE_THRESHOLD = 0.75;

    public IntentClassificationResult classifyIntent(ProcessedInput input) {
        String prompt = buildIntentClassificationPrompt(input);
        String llmResponse = llm.generate(prompt);
        
        return parseIntentClassificationResponse(llmResponse, input);
    }

    private String buildIntentClassificationPrompt(ProcessedInput input) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("# 生产排产智能助手 - 意图识别专家\n\n");
        
        prompt.append("## 意图分类体系\n");
        prompt.append("### 数据操作类 (DATA_OPERATIONS)\n");
        prompt.append("- REAL_TIME_QUERY: 查询实时生产数据、设备状态\n");
        prompt.append("- BATCH_QUERY: 批量查询历史数据、统计信息\n");
        prompt.append("- DATA_EXPORT: 数据导出、报表生成\n\n");
        
        prompt.append("### 分析操作类 (ANALYSIS_OPERATIONS)\n");
        prompt.append("- TREND_ANALYSIS: 趋势分析、变化对比\n");
        prompt.append("- PREDICTIVE_ANALYSIS: 预测分析、未来规划\n");
        prompt.append("- COMPARATIVE_ANALYSIS: 对比分析、基准测试\n\n");
        
        prompt.append("### 知识操作类 (KNOWLEDGE_OPERATIONS)\n");
        prompt.append("- KNOWLEDGE_SEARCH: 知识库搜索、技术文档查询\n");
        prompt.append("- PROCEDURE_LOOKUP: 操作流程、标准规范查询\n");
        prompt.append("- BEST_PRACTICE: 最佳实践、经验分享\n\n");
        
        prompt.append("### 执行操作类 (ACTION_OPERATIONS)\n");
        prompt.append("- SCHEDULE_OPTIMIZE: 生产排程优化\n");
        prompt.append("- ALERT_MANAGEMENT: 告警处理、异常管理\n");
        prompt.append("- REPORT_GENERATION: 自动报告生成\n\n");
        
        prompt.append("## 输入\n");
        prompt.append("用户输入: ").append(input.getCleanedInput()).append("\n");
        prompt.append("提取实体: ").append(input.getExtractedEntities()).append("\n\n");
        
        prompt.append("## 输出要求\n");
        prompt.append("返回JSON格式，包含：\n");
        prompt.append("{\n");
        prompt.append("  \"primaryIntent\": \"一级意图\",\n");
        prompt.append("  \"secondaryIntent\": \"二级意图\",\n");
        prompt.append("  \"confidence\": 0.95,\n");
        prompt.append("  \"entities\": [],\n");
        prompt.append("  \"parameters\": {},\n");
        prompt.append("  \"requiredTools\": [],\n");
        prompt.append("  \"reasoning\": \"识别推理过程\"\n");
        prompt.append("}\n");
        
        return prompt.toString();
    }

    private IntentClassificationResult parseIntentClassificationResponse(String response, ProcessedInput input) {
        // 解析LLM返回的JSON结果
        IntentClassificationResult result = new IntentClassificationResult();
        
        try {
            // 简化实现，实际应使用JSON解析库
            result.setPrimaryIntent(extractValue(response, "primaryIntent"));
            result.setSecondaryIntent(extractValue(response, "secondaryIntent"));
            result.setConfidence(Double.parseDouble(extractValue(response, "confidence")));
            result.setEntities(input.getExtractedEntities());
            result.setParameters(new HashMap<>());
            result.setRequiredTools(Arrays.asList("DatabaseQueryTool", "KnowledgeRAGTool"));
            result.setReasoning(extractValue(response, "reasoning"));
            
        } catch (Exception e) {
            // fallback逻辑
            result.setPrimaryIntent("KNOWLEDGE_OPERATIONS");
            result.setSecondaryIntent("KNOWLEDGE_SEARCH");
            result.setConfidence(0.5);
        }
        
        return result;
    }

    private String extractValue(String json, String key) {
        // 简化的JSON值提取
        String pattern = "\"" + key + "\"\\s*:\\s*\"([^\"]+)\"";
        java.util.regex.Pattern p = Pattern.compile(pattern);
        java.util.regex.Matcher m = p.matcher(json);
        return m.find() ? m.group(1) : "";
    }
}

/**
 * 工具注册表
 */
@Component
class ToolRegistry {
    
    private Map<String, List<Tool>> intentToolMapping;
    
    @Autowired
    private DatabaseQueryTool databaseQueryTool;
    
    @Autowired
    private KnowledgeRAGTool knowledgeRAGTool;
    
    @Autowired
    private MESConnectorTool mesConnectorTool;

    public ToolRegistry() {
        initializeToolMapping();
    }

    private void initializeToolMapping() {
        intentToolMapping = new HashMap<>();
        
        // 数据操作工具
        List<Tool> dataTools = Arrays.asList(databaseQueryTool, mesConnectorTool);
        intentToolMapping.put("DATA_OPERATIONS", dataTools);
        
        // 知识操作工具
        List<Tool> knowledgeTools = Arrays.asList(knowledgeRAGTool);
        intentToolMapping.put("KNOWLEDGE_OPERATIONS", knowledgeTools);
    }

    public List<Tool> selectTools(IntentClassificationResult intent) {
        List<Tool> selectedTools = new ArrayList<>();
        
        // 基于一级意图选择基础工具
        List<Tool> baseTools = intentToolMapping.get(intent.getPrimaryIntent());
        if (baseTools != null) {
            selectedTools.addAll(baseTools);
        }
        
        // 基于需要的工具列表补充
        for (String requiredTool : intent.getRequiredTools()) {
            Tool tool = findToolByName(requiredTool);
            if (tool != null && !selectedTools.contains(tool)) {
                selectedTools.add(tool);
            }
        }
        
        return selectedTools;
    }

    private Tool findToolByName(String toolName) {
        // 根据工具名称查找工具实例
        switch (toolName) {
            case "DatabaseQueryTool":
                return databaseQueryTool;
            case "KnowledgeRAGTool":
                return knowledgeRAGTool;
            case "MESConnectorTool":
                return mesConnectorTool;
            default:
                return null;
        }
    }
}

/**
 * 数据库查询工具
 */
@Tool("数据库查询工具")
@Component
class DatabaseQueryTool {
    
    @ToolMethod("执行SQL查询")
    public QueryResult executeSQLQuery(
        @ToolParam("数据源名称") String dataSource,
        @ToolParam("查询参数") Map<String, Object> queryParams,
        @ToolParam("安全级别") SecurityLevel securityLevel
    ) {
        QueryResult result = new QueryResult();
        
        try {
            // 实现SQL查询逻辑
            String sql = generateSQL(queryParams, dataSource);
            List<Map<String, Object>> data = executeQuery(sql, dataSource);
            
            result.setQueryResults(data);
            result.setTotalRows(data.size());
            result.setExecutionTime(System.currentTimeMillis());
            result.setDataSources(Arrays.asList(dataSource));
            
        } catch (Exception e) {
            result.setWarnings(Arrays.asList("查询执行失败: " + e.getMessage()));
        }
        
        return result;
    }

    private String generateSQL(Map<String, Object> params, String dataSource) {
        // 根据参数生成SQL
        return "SELECT * FROM production_orders WHERE status = 'ACTIVE' LIMIT 10";
    }

    private List<Map<String, Object>> executeQuery(String sql, String dataSource) {
        // 执行查询并返回结果
        List<Map<String, Object>> results = new ArrayList<>();
        Map<String, Object> row = new HashMap<>();
        row.put("order_no", "WO-001");
        row.put("product_id", "P-001");
        row.put("status", "ACTIVE");
        results.add(row);
        return results;
    }

    @ToolMethod("获取表结构信息")
    public SchemaInfo getTableSchema(@ToolParam("表名") String tableName) {
        // 获取表结构信息
        SchemaInfo schema = new SchemaInfo();
        schema.setTableName(tableName);
        schema.setColumns(Arrays.asList("id", "name", "status", "created_time"));
        return schema;
    }
}

/**
 * 知识库RAG工具
 */
@Tool("知识库查询工具")
@Component  
class KnowledgeRAGTool {
    
    @Autowired
    private EmbeddingStore<TextSegment> embeddingStore;
    
    @Autowired
    private EmbeddingModel embeddingModel;
    
    @Autowired
    private ChatLanguageModel chatModel;

    @ToolMethod("向量检索查询")
    public RetrievalResult vectorSearch(
        @ToolParam("查询文本") String query,
        @ToolParam("知识库类型") KnowledgeType knowledgeType,
        @ToolParam("检索数量") int topK,
        @ToolParam("相似度阈值") double similarityThreshold
    ) {
        RetrievalResult result = new RetrievalResult();
        
        try {
            // 1. 查询向量化
            Embedding queryEmbedding = embeddingModel.embed(query).content();
            
            // 2. 向量检索
            EmbeddingSearchRequest searchRequest = EmbeddingSearchRequest.builder()
                .queryEmbedding(queryEmbedding)
                .maxResults(topK)
                .minScore(similarityThreshold)
                .build();
                
            EmbeddingSearchResult<TextSegment> searchResult = embeddingStore.search(searchRequest);
            
            // 3. 构建检索结果
            List<Document> retrievedDocs = searchResult.matches().stream()
                .map(match -> new Document(match.embedded().text()))
                .collect(Collectors.toList());
                
            // 4. 生成RAG回答
            String ragAnswer = generateRAGAnswer(query, retrievedDocs);
            
            result.setDocuments(retrievedDocs);
            result.setAnswer(ragAnswer);
            result.setConfidence(calculateRAGConfidence(searchResult));
            result.setKnowledgeType(knowledgeType);
            
        } catch (Exception e) {
            result.setAnswer("知识库查询失败: " + e.getMessage());
            result.setConfidence(0.0);
        }
        
        return result;
    }

    private String generateRAGAnswer(String query, List<Document> documents) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("# 生产知识库专家 - RAG增强回答生成器\n\n");
        prompt.append("## 用户问题\n");
        prompt.append(query).append("\n\n");
        
        prompt.append("## 检索到的相关文档\n");
        for (int i = 0; i < documents.size(); i++) {
            prompt.append("### 文档 ").append(i + 1).append("\n");
            prompt.append(documents.get(i).text()).append("\n\n");
        }
        
        prompt.append("## 回答要求\n");
        prompt.append("基于以上文档内容，为用户提供准确、专业的回答。\n");
        
        return chatModel.generate(prompt.toString());
    }

    private double calculateRAGConfidence(EmbeddingSearchResult<TextSegment> searchResult) {
        if (searchResult.matches().isEmpty()) {
            return 0.0;
        }
        
        double avgScore = searchResult.matches().stream()
            .mapToDouble(EmbeddingMatch::score)
            .average()
            .orElse(0.0);
            
        return Math.min(avgScore, 1.0);
    }

    @ToolMethod("混合检索查询")
    public RetrievalResult hybridSearch(
        @ToolParam("查询文本") String query,
        @ToolParam("关键词列表") List<String> keywords,
        @ToolParam("过滤条件") Map<String, Object> filters
    ) {
        // 实现混合检索逻辑
        return vectorSearch(query, KnowledgeType.BEST_PRACTICES, 5, 0.7);
    }
}

/**
 * MES系统连接器工具
 */
@Tool("MES系统连接器")
@Component
class MESConnectorTool {
    
    @ToolMethod("查询生产工单")
    public List<WorkOrder> queryWorkOrders(@ToolParam("查询条件") WorkOrderFilter filter) {
        // 模拟MES系统查询
        List<WorkOrder> workOrders = new ArrayList<>();
        WorkOrder wo = new WorkOrder();
        wo.setOrderNo("WO-001");
        wo.setProductId("P-001");
        wo.setStatus("IN_PROGRESS");
        wo.setQuantity(100);
        workOrders.add(wo);
        return workOrders;
    }

    @ToolMethod("获取设备状态")
    public EquipmentStatus getEquipmentStatus(@ToolParam("设备ID") String equipmentId) {
        // 模拟设备状态查询
        EquipmentStatus status = new EquipmentStatus();
        status.setEquipmentId(equipmentId);
        status.setStatus("RUNNING");
        status.setUtilizationRate(85.5);
        status.setLastMaintenance(LocalDateTime.now().minusDays(7));
        return status;
    }
}

/**
 * Few-Shot示例存储
 */
@Component
class FewShotExampleStore {
    
    private Map<String, Map<String, List<String>>> examples;

    public FewShotExampleStore() {
        initializeExamples();
    }

    private void initializeExamples() {
        examples = new HashMap<>();
        
        Map<String, List<String>> dataOperations = new HashMap<>();
        dataOperations.put("REAL_TIME_QUERY", Arrays.asList(
            "查询当前设备A的运行状态",
            "现在的生产线效率如何",
            "今天完成了多少订单"
        ));
        dataOperations.put("BATCH_QUERY", Arrays.asList(
            "导出上个月的所有生产数据",
            "统计Q1季度的设备故障记录"
        ));
        
        examples.put("DATA_OPERATIONS", dataOperations);
        
        Map<String, List<String>> knowledgeOperations = new HashMap<>();
        knowledgeOperations.put("KNOWLEDGE_SEARCH", Arrays.asList(
            "如何操作CNC机床",
            "质量检验的标准流程是什么"
        ));
        knowledgeOperations.put("BEST_PRACTICE", Arrays.asList(
            "提高生产效率的最佳做法",
            "设备维护的行业标准"
        ));
        
        examples.put("KNOWLEDGE_OPERATIONS", knowledgeOperations);
    }

    public Map<String, Map<String, List<String>>> getExamples() {
        return examples;
    }
}

/**
 * 配置类
 */
@Configuration
class ProductionAgentConfig {
    
    @Value("${openai.api.key}")
    private String openAiApiKey;

    @Bean
    public ChatLanguageModel chatLanguageModel() {
        return OpenAiChatModel.builder()
            .apiKey(openAiApiKey)
            .modelName("gpt-4-turbo")
            .temperature(0.3)
            .maxTokens(2048)
            .timeout(Duration.ofSeconds(30))
            .build();
    }

    @Bean
    public EmbeddingModel embeddingModel() {
        return OpenAiEmbeddingModel.builder()
            .apiKey(openAiApiKey)
            .modelName("text-embedding-ada-002")
            .build();
    }

    @Bean
    public EmbeddingStore<TextSegment> embeddingStore() {
        return ChromaEmbeddingStore.builder()
            .baseUrl("http://localhost:8000")
            .collectionName("production-knowledge")
            .build();
    }

    @Bean
    public DocumentSplitter documentSplitter() {
        return DocumentSplitters.recursive(500, 50);
    }
}

// ==================== 数据模型类 ====================

/**
 * 用户请求
 */
class UserRequest {
    private String userInput;
    private String sessionId;
    private String userId;
    private Long timestamp;
    private Map<String, String> headers;
    private UserContext userContext;
    
    // getter/setter方法
    public String getUserInput() { return userInput; }
    public void setUserInput(String userInput) { this.userInput = userInput; }
    public String getSessionId() { return sessionId; }
    public void setSessionId(String sessionId) { this.sessionId = sessionId; }
    public String getUserId() { return userId; }
    public void setUserId(String userId) { this.userId = userId; }
    public Long getTimestamp() { return timestamp; }
    public void setTimestamp(Long timestamp) { this.timestamp = timestamp; }
    public Map<String, String> getHeaders() { return headers; }
    public void setHeaders(Map<String, String> headers) { this.headers = headers; }
    public UserContext getUserContext() { return userContext; }
    public void setUserContext(UserContext userContext) { this.userContext = userContext; }
}

/**
 * 处理后的输入
 */
class ProcessedInput {
    private String cleanedInput;
    private List<String> extractedEntities;
    private Map<String, Object> metadata;
    private boolean isValid;
    private double confidenceScore;
    private List<String> warnings;
    
    // getter/setter方法
    public String getCleanedInput() { return cleanedInput; }
    public void setCleanedInput(String cleanedInput) { this.cleanedInput = cleanedInput; }
    public List<String> getExtractedEntities() { return extractedEntities; }
    public void setExtractedEntities(List<String> extractedEntities) { this.extractedEntities = extractedEntities; }
    public Map<String, Object> getMetadata() { return metadata; }
    public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; }
    public boolean isValid() { return isValid; }
    public void setValid(boolean valid) { isValid = valid; }
    public double getConfidenceScore() { return confidenceScore; }
    public void setConfidenceScore(double confidenceScore) { this.confidenceScore = confidenceScore; }
    public List<String> getWarnings() { return warnings; }
    public void setWarnings(List<String> warnings) { this.warnings = warnings; }
}

/**
 * 意图识别结果
 */
class IntentClassificationResult {
    private String primaryIntent;
    private String secondaryIntent;
    private double confidence;
    private List<String> entities;
    private Map<String, Object> parameters;
    private List<String> requiredTools;
    private String reasoning;
    private List<String> alternatives;
    
    // getter/setter方法
    public String getPrimaryIntent() { return primaryIntent; }
    public void setPrimaryIntent(String primaryIntent) { this.primaryIntent = primaryIntent; }
    public String getSecondaryIntent() { return secondaryIntent; }
    public void setSecondaryIntent(String secondaryIntent) { this.secondaryIntent = secondaryIntent; }
    public double getConfidence() { return confidence; }
    public void setConfidence(double confidence) { this.confidence = confidence; }
    public List<String> getEntities() { return entities; }
    public void setEntities(List<String> entities) { this.entities = entities; }
    public Map<String, Object> getParameters() { return parameters; }
    public void setParameters(Map<String, Object> parameters) { this.parameters = parameters; }
    public List<String> getRequiredTools() { return requiredTools; }
    public void setRequiredTools(List<String> requiredTools) { this.requiredTools = requiredTools; }
    public String getReasoning() { return reasoning; }
    public void setReasoning(String reasoning) { this.reasoning = reasoning; }
    public List<String> getAlternatives() { return alternatives; }
    public void setAlternatives(List<String> alternatives) { this.alternatives = alternatives; }
}

/**
 * 工具执行结果
 */
class ToolExecutionResult {
    private Map<String, Object> toolResults;
    private long executionTime;
    
    // getter/setter方法
    public Map<String, Object> getToolResults() { return toolResults; }
    public void setToolResults(Map<String, Object> toolResults) { this.toolResults = toolResults; }
    public long getExecutionTime() { return executionTime; }
    public void setExecutionTime(long executionTime) { this.executionTime = executionTime; }
}

/**
 * 工作流响应
 */
class WorkflowResponse {
    private String answer;
    private String intent;
    private double confidence;
    private long executionTime;
    private List<String> sources;
    
    // getter/setter方法
    public String getAnswer() { return answer; }
    public void setAnswer(String answer) { this.answer = answer; }
    public String getIntent() { return intent; }
    public void setIntent(String intent) { this.intent = intent; }
    public double getConfidence() { return confidence; }
    public void setConfidence(double confidence) { this.confidence = confidence; }
    public long getExecutionTime() { return executionTime; }
    public void setExecutionTime(long executionTime) { this.executionTime = executionTime; }
    public List<String> getSources() { return sources; }
    public void setSources(List<String> sources) { this.sources = sources; }
}

/**
 * 查询结果
 */
class QueryResult {
    private List<Map<String, Object>> queryResults;
    private QueryMetadata metadata;
    private List<String> dataSources;
    private long executionTime;
    private int totalRows;
    private List<String> warnings;
    private Map<String, Object> aggregations;
    
    // getter/setter方法
    public List<Map<String, Object>> getQueryResults() { return queryResults; }
    public void setQueryResults(List<Map<String, Object>> queryResults) { this.queryResults = queryResults; }
    public QueryMetadata getMetadata() { return metadata; }
    public void setMetadata(QueryMetadata metadata) { this.metadata = metadata; }
    public List<String> getDataSources() { return dataSources; }
    public void setDataSources(List<String> dataSources) { this.dataSources = dataSources; }
    public long getExecutionTime() { return executionTime; }
    public void setExecutionTime(long executionTime) { this.executionTime = executionTime; }
    public int getTotalRows() { return totalRows; }
    public void setTotalRows(int totalRows) { this.totalRows = totalRows; }
    public List<String> getWarnings() { return warnings; }
    public void setWarnings(List<String> warnings) { this.warnings = warnings; }
    public Map<String, Object> getAggregations() { return aggregations; }
    public void setAggregations(Map<String, Object> aggregations) { this.aggregations = aggregations; }
}

/**
 * 检索结果
 */
class RetrievalResult {
    private List<Document> documents;
    private String answer;
    private double confidence;
    private KnowledgeType knowledgeType;
    
    // getter/setter方法
    public List<Document> getDocuments() { return documents; }
    public void setDocuments(List<Document> documents) { this.documents = documents; }
    public String getAnswer() { return answer; }
    public void setAnswer(String answer) { this.answer = answer; }
    public double getConfidence() { return confidence; }
    public void setConfidence(double confidence) { this.confidence = confidence; }
    public KnowledgeType getKnowledgeType() { return knowledgeType; }
    public void setKnowledgeType(KnowledgeType knowledgeType) { this.knowledgeType = knowledgeType; }
}

// ==================== 枚举类 ====================

/**
 * 实体类型枚举
 */
enum EntityType {
    EQUIPMENT("设备", Pattern.compile("设备[A-Z0-9]+")),
    TIME_RANGE("时间范围", Pattern.compile("(今天|昨天|本周|上月|\\d+天前)")),
    PRODUCTION_LINE("生产线", Pattern.compile("生产线[0-9]+")),
    PRODUCT_TYPE("产品类型", Pattern.compile("产品[A-Z0-9]+")),
    METRIC_TYPE("指标类型", Pattern.compile("(效率|产量|质量|成本)"));

    private final String displayName;
    private final Pattern pattern;

    EntityType(String displayName, Pattern pattern) {
        this.displayName = displayName;
        this.pattern = pattern;
    }

    public String getDisplayName() { return displayName; }
    public Pattern getPattern() { return pattern; }
}

/**
 * 知识库类型枚举
 */
enum KnowledgeType {
    PROCESS_STANDARDS("工艺标准", "production_process"),
    EQUIPMENT_MANUALS("设备手册", "equipment_docs"),
    QUALITY_STANDARDS("质量标准", "quality_control"),
    SAFETY_PROCEDURES("安全规程", "safety_docs"),
    BEST_PRACTICES("最佳实践", "best_practices"),
    TROUBLESHOOTING("故障排除", "troubleshooting"),
    MAINTENANCE_GUIDES("维护指南", "maintenance");

    private final String displayName;
    private final String collectionName;

    KnowledgeType(String displayName, String collectionName) {
        this.displayName = displayName;
        this.collectionName = collectionName;
    }

    public String getDisplayName() { return displayName; }
    public String getCollectionName() { return collectionName; }
}

/**
 * 安全级别枚举
 */
enum SecurityLevel {
    LOW, STANDARD, HIGH, CRITICAL
}

// ==================== 其他数据类 ====================

class UserContext {
    private String role;
    private String department;
    private List<String> permissions;
    
    // getter/setter方法
    public String getRole() { return role; }
    public void setRole(String role) { this.role = role; }
    public String getDepartment() { return department; }
    public void setDepartment(String department) { this.department = department; }
    public List<String> getPermissions() { return permissions; }
    public void setPermissions(List<String> permissions) { this.permissions = permissions; }
}

class QueryMetadata {
    private String queryId;
    private long startTime;
    private long endTime;
    private String queryType;
    
    // getter/setter方法
    public String getQueryId() { return queryId; }
    public void setQueryId(String queryId) { this.queryId = queryId; }
    public long getStartTime() { return startTime; }
    public void setStartTime(long startTime) { this.startTime = startTime; }
    public long getEndTime() { return endTime; }
    public void setEndTime(long endTime) { this.endTime = endTime; }
    public String getQueryType() { return queryType; }
    public void setQueryType(String queryType) { this.queryType = queryType; }
}

class SchemaInfo {
    private String tableName;
    private List<String> columns;
    
    // getter/setter方法
    public String getTableName() { return tableName; }
    public void setTableName(String tableName) { this.tableName = tableName; }
    public List<String> getColumns() { return columns; }
    public void setColumns(List<String> columns) { this.columns = columns; }
}

class WorkOrder {
    private String orderNo;
    private String productId;
    private String status;
    private int quantity;
    
    // getter/setter方法
    public String getOrderNo() { return orderNo; }
    public void setOrderNo(String orderNo) { this.orderNo = orderNo; }
    public String getProductId() { return productId; }
    public void setProductId(String productId) { this.productId = productId; }
    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }
    public int getQuantity() { return quantity; }
    public void setQuantity(int quantity) { this.quantity = quantity; }
}

class WorkOrderFilter {
    private String status;
    private String productId;
    private LocalDateTime startTime;
    private LocalDateTime endTime;
    
    // getter/setter方法
    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }
    public String getProductId() { return productId; }
    public void setProductId(String productId) { this.productId = productId; }
    public LocalDateTime getStartTime() { return startTime; }
    public void setStartTime(LocalDateTime startTime) { this.startTime = startTime; }
    public LocalDateTime getEndTime() { return endTime; }
    public void setEndTime(LocalDateTime endTime) { this.endTime = endTime; }
}

class EquipmentStatus {
    private String equipmentId;
    private String status;
    private double utilizationRate;
    private LocalDateTime lastMaintenance;
    
    // getter/setter方法
    public String getEquipmentId() { return equipmentId; }
    public void setEquipmentId(String equipmentId) { this.equipmentId = equipmentId; }
    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }
    public double getUtilizationRate() { return utilizationRate; }
    public void setUtilizationRate(double utilizationRate) { this.utilizationRate = utilizationRate; }
    public LocalDateTime getLastMaintenance() { return lastMaintenance; }
    public void setLastMaintenance(LocalDateTime lastMaintenance) { this.lastMaintenance = lastMaintenance; }
}
